// Package app 将程序注册为服务
package app

import (
	"context"
	"github.com/kardianos/service"
	"github.com/sirupsen/logrus"
	"os"
	"runtime"
)

const (
	serviceName        = cliName
	serviceDisplay     = cliName
	serviceDescription = cliUsage
)

func NewService() (serv service.Service, err error) {
	servConf := &service.Config{
		Name:             serviceName,
		DisplayName:      serviceDisplay,
		Description:      serviceDescription,
		Arguments:        []string{},
		Executable:       "",
		Dependencies:     nil,
		WorkingDirectory: "",
		ChRoot:           "",
		Option:           nil,
		EnvVars:          nil,
	}
	switch runtime.GOOS {
	case "darwin":
		servConf.Option = service.KeyValue{
			"KeepAlive":   true,
			"RunAtLoad":   true,
			"UserService": os.Getuid() != 0,
		}
	}
	m := new(manager)
	return service.New(m, servConf)
}

// 管理器管理服务生命周期。
type manager struct {
	cancel     context.CancelFunc
	configFile *string
}

// Start starts the service in a separate go routine.
func (m *manager) Start(service.Service) error {
	defer func() {
		logrus.Debug("manager Start2")
	}()
	logrus.Debug("manager Start1")
	go m.run()
	return nil
}

// Stop stops the service.
func (m *manager) Stop(service.Service) error {
	defer func() {
		logrus.Debug("manager Stop 2")
	}()
	logrus.Debug("manager Stop 1")
	m.cancel()
	return nil
}

func (m *manager) run() {
	ctx, cancel := context.WithCancel(context.Background())
	m.cancel = cancel
	ctx = WithContextFunc(ctx, func() {
		cancel()
	})
	daem := NewDaemon()
	daem.Run(ctx)
}
